var map = null;
var geocoder = null;

var paths = [];
var polygonEdit = null;

//var g = google.maps;
var marker = null;
var label = null;
//selected vh_id
var vh_id = null;
//selected user id
var user_id = 0;
var polygons = [];
var requestHandler = null;
var lines = [];
var measureTool = false;
var clickCount = 0;
var polyline = null;
var polygon = null;
var clickMapHandler = null;
var calculateArea = false;
var bgColor = '';
var formGeofence = null;
var dlgGeofence = null;

var lokalOpt = {
    getTileUrl: function(coord, zoom) {
        return "http://tiles.navigasi.net/navnet-hybrid/" + zoom + "/" + coord.x + "/" + coord.y + ".png";
    },
    tileSize: new google.maps.Size(256, 256),
    isPng: true,
    maxZoom: 18,
    minZoom: 0,
    name: "Lokal"
};
var lokalType = new google.maps.ImageMapType(lokalOpt);
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
init_map = function() {
    var mapOptions = {
        zoom: 5,
        center: new google.maps.LatLng(-0.789275, 113.921327),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControlOptions: {
            mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, 'Lokal']
        }
    };
    geocoder = new google.maps.Geocoder();
    map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
    map.mapTypes.set('Lokal', lokalType);
};

reset_bg_toolbar_button = function() {
    $("#btn_measure_area").css("background-color", bgColor);
    $("#btn_measure_distance").css("background-color", bgColor);
    $("#btn_zoomall").css("background-color", bgColor);
    $("#btn_zoomin").css("background-color", bgColor);
    $("#btn_zoomout").css("background-color", bgColor);
};
enable_measure_area_tool = function() {
    reset_bg_toolbar_button();
    close_measure_tool();
    if (calculateArea === true) {
        calculateArea = false;
        close_measure_tool();
        return;
    }
    dlgGeofence.dialog('open');
    //Clear existing previous tool
    polygon = new google.maps.Polygon({
        map: map,
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#FF0000',
        fillOpacity: 0.35,
        draggable: true,
        editable: true,
        geodesic: true
    });
    clickMapHandler = google.maps.event.addListener(map, 'click', addLocation2);
    $("#text_measure").show();
    $("#btn_measure_area").css("background-color", '#ff0000');
    calculateArea = true;
};

enable_measure_line_tool = function() {
    reset_bg_toolbar_button();
    close_measure_tool();
    if (calculateDistance === true) {
        calculateDistance = false;
        return;
    }
    //Clear existing previous tool
    close_measure_tool();
    var polyOptions = {
        strokeColor: '#FF0000',
        strokeOpacity: 1.0,
        strokeWeight: 3
    };
    polyline = new google.maps.Polyline(polyOptions);
    polyline.setMap(map);
    clickMapHandler = google.maps.event.addListener(map, 'click', addLocation);
    $("#btn_measure_distance").css("background-color", '#ff0000');
    $("#text_measure").show();
    calculateDistance = true;
};
close_measure_tool = function() {
    if (polyline !== null) {
        clearPaths();
        polyline.setMap(null);
    }
    if (polygon !== null) {
        polygon.setMap(null);
    }
    if (clickMapHandler !== null) {
        google.maps.event.removeListener(clickMapHandler);
    }
    $("#text_measure").hide();
};
function addLocation(event) {
    var path = polyline.getPath();
    path.push(event.latLng);
    var distance = google.maps.geometry.spherical.computeLength(path.getArray()) / 1000;
    document.getElementById('text_measure').value = "Jarak " + distance.toFixed(2) + " Km";
}
function addLocation2(event) {
    var path = polygon.getPath();
    path.push(event.latLng);
    var distance = google.maps.geometry.spherical.computeArea(path.getArray()) / 1000;
    document.getElementById('text_measure').value = "Luas " + distance.toFixed(2) + " Km2";
}
function clearPaths() {
    var path = polyline.getPath();
    while (path.getLength()) {
        path.pop();
    }
}

map_label = function(id, nopol, marker)
{
    var label = new Label({
        id: id,
        map: map
    });
    label.bindTo('position', marker, 'position');
    label.set('text', nopol);

//    console.log(labels[id]);
//    if( (labels[id]!==null) || (labels[id] !=='undefined')){
//        label.setMap(labels[id].getMap());
//    }
    return label;
};
dName = function(a) {
    if ((a >= 337.5) && (a >= 0) && (a <= 22))
        return "Utara";
    if ((a >= 22.5) && (a <= 67))
        return "Timur Laut";
    if ((a >= 67.5) && (a <= 112))
        return "Timur";
    if ((a >= 112.5) && (a <= 157))
        return "Tenggara";
    if ((a >= 157.5) && (a <= 202))
        return "Selatan";
    if ((a >= 202.5) && (a <= 247))
        return "Barat Daya";
    if ((a >= 247.5) && (a <= 292))
        return "Barat";
    if ((a >= 292.5) && (a <= 337))
        return "Barat Laut";
};

create_marker = function(id, lat, lng, icon_type, speed, angle) {
    var myLatLng = new google.maps.LatLng(lat, lng);
    var marker = new google.maps.Marker({
        title: id,
        position: myLatLng,
        map: map,
        icon: 'images/gps/' + create_icon(icon_type, speed, angle)
    });

    google.maps.event.addListener(marker, 'click', function() {
        selectedMarker = marker;
        selectedMarkerId = id;
        if (infoWindow !== null)
            infoWindow.close();
        infoWindow = new google.maps.InfoWindow({
            content: get_infoWindow(id)
        });
        infoWindow.open(map, marker);
    });
    return marker;
};
clear_marker = function() {
    if (markers) {
        for (i in markers) {
            markers[i].setMap(null);
        }
        markers.length = 0;
    }

    if (labels) {
        for (i in labels) {
            labels[i].setMap(null);
        }
        labels.length = 0;
    }

    if (polyline) {
        polyline_clear();
    }
};

clear_tracks = function() {
    if (tracksicon) {
        for (i in tracksicon) {
            tracksicon[i].setMap(null);
        }
        tracksicon.length = 0;
    }
    if (polyline) {
        polyline_clear();
    }
    tracks = [];
};
create_icon = function(icon_type, s, a)
{
    return icon_type + '/' + icon_type + '.png';
//    var state = 'run.gif';
//    if (s <= 0)
//        state = 'stop.gif';
//    if (icon_type !== 'orang') {
//        if ((a >= 337.5) || ((a >= 0) && (a <= 22)))
//            return icon_type + "/0-" + state;
//        if ((a >= 22.5) && (a <= 67))
//            return icon_type + "/45-" + state;
//        if ((a >= 67.5) && (a <= 112))
//            return icon_type + "/90-" + state;
//        if ((a >= 112.5) && (a <= 157))
//            return icon_type + "/135-" + state;
//        if ((a >= 157.5) && (a <= 202))
//            return icon_type + "/180-" + state;
//        if ((a >= 202.5) && (a <= 247))
//            return icon_type + "/225-" + state;
//        if ((a >= 247.5) && (a <= 292))
//            return icon_type + "/270-" + state;
//        if ((a >= 292.5) && (a <= 337))
//            return icon_type + "/315-" + state;
//        else
//            return "default/icon.gif";
//    } else {
//        return icon_type + "/orang.png";
//    }
    // console.log("Angle:"+ a+" * "+  icon_type+"/0-"+state);
};
/*******************************************/
/*          POLYGON /GEOFENCE              */
/*******************************************/
load_geofence = function(im) {
    console.log("Load Geofence,Imei:" + im);
    clear_geofence();
    reqHandler = $.post('php_script/get_geofence.php', {imei: im},
    function(data, status) {
        if (status === 'success') {
            console.log(status);
            var html = "";
            data = $.parseJSON(data);
            var no = 1;
            html = "<table class='tblg'><tr><td class='w50'>No</td><td class='w100'>Nama</td><td class='w100'>Luas</td><td class='w100'>Operate</td></tr>";
            $.each(data, function(i, item) {
                draw_geofence(item.id, item.imei, item.name, item.geofence);
                html = html + "<tr><td>" + no + "</td><td>" + item.name + "</td><td>" + item.luas + "</td><td><a href='#' onClick='del_geofence(" + item.id + ");'>Del</a>&nbsp;|&nbsp;<a href='#' onClick='edit_geofence(" + item.id + ");'>Edit</a></td></tr>";
                no++;
            });
            html = html + "</table>";
            $("#cpolygon").html(html);

        }
    }
    );
};
draw_geofence = function(id, imei, name, arr) {
    var path = [];
    var coor = arr.split(",");

    for (i = 0; i < coor.length; i++) {
        var ll = coor[i].split(" ");
        var lat = parseFloat(ll[0]);
        var lng = parseFloat(ll[1]);
        path.push(new google.maps.LatLng(lat, lng));
    }
    var p = new google.maps.Polygon({
        paths: path,
        editable: false,
        strokeColor: "#FF0000",
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: "#FF0000",
        fillOpacity: 0.35
    });

    p.setMap(map);
    var pObject = {
        id: id,
        imei: imei,
        name: name,
        state: '',
        polygon: p
    };

    polygons.push(pObject);
};
find_geofence = function(id) {
    var p = null;
    if (polygons) {
        for (i in polygons) {
            if (polygons[i].id === id) {
                p = polygons[i];
            } else {
                polygons[i].polygon.setVisible(false);
            }
        }
    }
    return p;
};
new_geofence = function() {


    if ((selectedMarker === null) || (selectedMarkerId <= 0)) {
        alert('Pilih Kendaraan/Nopol Lebih Dulu');
        return;
    }
    var imei = r.imei;
    var path = [];
    var center = map.getCenter(); //getPosition();
    var x1 = center.lng() - 0.1;
    var x2 = center.lng() + 0.1;
    var y1 = center.lat() - 0.1;
    var y2 = center.lat() + 0.1;
    path.push(new google.maps.LatLng(y1, x1));
    path.push(new google.maps.LatLng(y1, x2));
    path.push(new google.maps.LatLng(y2, x2));
    path.push(new google.maps.LatLng(y2, x1));


    var p = new google.maps.Polygon({
        paths: path,
        editable: true,
        draggable: true,
        strokeColor: "#FF0000",
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: "#FF0000",
        fillOpacity: 0.35
    });

    p.setMap(map);
    polygonEdit = {
        id: '',
        imei: imei,
        state: 'new',
        polygon: p,
        name: ''
    };
    //polygonEdit=pObject;
    //$("#btn_load").hide();
    $("#btn_new").hide();
    $("#btn_clear").hide();
    $("#btn_save").show();
    $("#btn_cancel").show();
    //$("#btn_update").hide();
};
edit_geofence = function(id)
{
    if (polygonEdit !== null) {
        alert(polygonEdit.state + ' State');
        return;
    }
    polygonEdit = find_geofence(id);
    //console.log(po);
    if (polygonEdit !== null) {
        polygonEdit.polygon.setEditable(true);
        polygonEdit.polygon.setDraggable(true);
        polygonEdit.state = 'edit';
    }
    $("#btn_new").hide();
    $("#btn_clear").hide();
    $("#btn_save").show();
    $("#btn_cancel").show();
};
save_geofence = function() {

    var path = polygon.getPath();//.getArray();
    //console.log(path.getArray());
    var arr = path.getArray();
    var paths = [];
    if (arr) {
        for (i in arr) {
            //console.log(arr[i].lat() + " " + arr[i].lng());
            latlng.push(arr[i].lat() + " " + arr[i].lng());
        }
    }
    //var name =         
    var polygon_name = $("#polygon_name").val();
    var description = $("#polygon_name").val();
    if (polygon_name !== '')
    {
        //console.log(latlng);

        $.post('php_script/save_geofence.php', {id: polygon_id, vh: vh_id, name: polygon_name, description: description, state: polygon_state, paths: paths},
        function(result) {
            console.log(result);
            polygon.setMap(null);           
        });
    }
};
cancel_geofence = function() {
    polygon_state = 'none';
    if (polygonEdit.polygon !== null) {
        polygonEdit.polygon.setMap(null);
        polygonEdit = null;
    }
    //$("#btn_load").show();
    $("#btn_new").show();
    $("#btn_clear").show();
    $("#btn_save").hide();
    $("#btn_update").hide();
    $("#btn_cancel").hide();
};
clear_geofence = function() {
    if (polygonEdit !== null) {
        polygonEdit.polygon.setMap(null);
        polygonEdit = null;
    }
    if (polygons) {
        for (i in polygons) {
            polygons[i].polygon.setMap(null);
            polygons[i].polygon = null;
        }
    }
    polygons = [];

    $("#btn_load").show();
    $("#btn_new").show();
    $("#btn_clear").show();
    $("#btn_save").hide();
    $("#btn_update").hide();
    $("#btn_cancel").hide();
    $("#right").html("");
};
del_geofence = function(id) {
    $.post('php/del_polygon.php', {id: id},
    function(result) {
        load_geofence();
        alert(result);
    }
    );
};
default_polygon_button = function() {
    $("#btn_load").show();
    $("#btn_new").show();
    $("#btn_clear").show();
    $("#btn_save").hide();
    $("#btn_update").hide();
    $("#btn_cancel").hide();
    $("#cpolygon").html("");
};